<template>
  <div class="ai-translation">
    <!-- 加载遮罩 -->
    <div class="loading-overlay" v-if="loading">
      <div class="loading-content">
        <div class="spinner-border text-primary spinner" role="status"></div>
        <div>正在生成中，请稍候...</div>
        <small class="text-muted">预计需要15秒</small>
      </div>
    </div>

    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/english/ai-exercise" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">AI生成的翻译题</h5>
      <span class="ai-badge">
        <i class="bi bi-robot"></i> AI生成
      </span>
    </div>

    <!-- 目标词汇展示 -->
    <div class="vocab-list">
      <div class="mb-2">使用的目标词汇：</div>
      <span v-for="vocab in vocabList" 
        :key="vocab.word" 
        class="vocab-item"
        @click="showVocabDetail(vocab)"
      >{{ vocab.word }}</span>
    </div>

    <!-- 添加单词详情 Modal -->
    <div class="modal fade" id="vocabDetailModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">单词详情</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" v-if="selectedVocab">
            <div class="vocab-detail-card">
              <div class="word-header">
                <h3 class="word">{{ selectedVocab.word }}</h3>
              </div>
              <div class="definition-section">
                <div class="section-label">英文释义：</div>
                <div class="english-definition">{{ selectedVocab.english_definition }}</div>
              </div>
              <div class="translation-section">
                <div class="section-label">中文翻译：</div>
                <div class="english-definition">{{ selectedVocab.chinese_translation }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 翻译内容 -->
    <div class="translation-section">
      <div class="english-text" v-html="highlightVocabs(translationText)"></div>
      
      <!-- 你的翻译 -->
      <template v-if="!showingReference">
        <div class="form-label">你的翻译：</div>
        <textarea 
          class="translation-input" 
          placeholder="请输入你的翻译..."
          v-model="userTranslation"
        ></textarea>
      </template>
      
      <!-- 参考译文和词汇解释 -->
      <template v-else>
        <div class="reference-section">
          <h6 class="section-title">参考译文</h6>
          <div class="reference-text">{{ chineseTranslation }}</div>
          
          <h6 class="section-title mt-4">词汇解释</h6>
          <div class="vocab-explanations">
            <div v-for="vocab in vocabList" :key="vocab.word" class="vocab-explanation">
              <div class="vocab-word">{{ vocab.word }}</div>
              <div class="vocab-details">
                <div class="english-def">{{ vocab.english_definition }}</div>
                <div class="chinese-trans">{{ vocab.chinese_translation }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools position-fixed bottom-0 w-100 bg-white p-3">
      <div class="d-flex justify-content-between align-items-center">
        <button class="regenerate-btn" 
          @click="regenerateContent"
          :disabled="isRegenerating"
        >
          <i class="bi bi-arrow-clockwise"></i>
          {{ isRegenerating ? '生成中...' : '重新生成' }}
        </button>
        <div>
          <!-- 保存按钮，只在输入模式下显示 -->
          <button 
            v-if="!showingReference && userTranslation.trim()"
            class="btn btn-success me-2"
            @click="saveTranslation"
            :disabled="isSaving"
          >
            <i class="bi bi-check-circle me-1"></i>
            {{ isSaving ? '保存中...' : '保存答案' }}
          </button>
          <button 
            class="btn" 
            :class="showingReference ? 'btn-outline-primary' : 'btn-primary'"
            @click="toggleReference"
          >
            {{ showingReference ? '返回翻译' : '查看参考译文' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/router/http'
import * as bootstrap from 'bootstrap'

export default {
  name: 'AITranslationView',
  
  data() {
    return {
      isRegenerating: false,
      vocabList: [],
      translationText: '',
      userTranslation: '',
      chineseTranslation: '',
      loading: true,
      showingReference: false,
      selectedVocab: null,
      vocabCount: 10,
      vocabModal: null,
      isSaving: false,
      isFirstLoad: true
    }
  },

  async created() {
    try {
      // 从 query 参数获取单词数量
      this.vocabCount = parseInt(this.$route.query.vocabCount) || 10
      
      // 首次加载时生成内容
      if (this.isFirstLoad) {
        await this.generateTranslation()
        this.isFirstLoad = false
      }
    } catch (error) {
      console.error('生成练习失败:', error)
      alert(error.message || '生成练习失败，请重试')
      // 发生错误时返回上一页
      this.$router.back()
    } finally {
      this.loading = false
    }
  },

  mounted() {
    // 初始化 Modal
    this.vocabModal = new bootstrap.Modal(document.getElementById('vocabDetailModal'))
  },

  methods: {
    async generateTranslation() {
      // 如果不是首次加载，则显示加载状态
      if (!this.isFirstLoad) {
        this.loading = true
      }

      try {
        // 获取生词列表
        const vocabResponse = await http.get('/student/vocabularyList/select')
        
        if (vocabResponse.data.code !== 1) {
          throw new Error(vocabResponse.data.message || '获取生词列表失败')
        }
        
        // 随机选择指定数量的生词
        const selectedVocabs = this.getRandomVocabs(vocabResponse.data.response, this.vocabCount)
        
        // 调用生成文章的接口
        const response = await http.post('/student/ai/forward/english/generate_article', {
          words: selectedVocabs
        })
        
        if (response.data.code !== 1) {
          throw new Error(response.data.message || 'Failed to generate exercise')
        }
        
        // 设置内容
        const data = response.data.response
        this.translationText = data.summary.article.english_content
        this.chineseTranslation = data.summary.article.chinese_content
        this.vocabList = data.summary.vocabulary_analysis
      } catch (error) {
        throw error // 向上传递错误，让调用者处理
      } finally {
        if (!this.isFirstLoad) {
          this.loading = false
        }
      }
    },

    // 修改重新生成方法
    async regenerateContent() {
      this.isRegenerating = true
      try {
        await this.generateTranslation()
        this.userTranslation = '' // 清空用户输入
        this.showingReference = false // 切换回翻译模式
      } catch (error) {
        console.error('重新生成失败:', error)
        alert(error.message || '重新生成失败，请重试')
      } finally {
        this.isRegenerating = false
      }
    },

    highlightVocabs(text) {
      let highlightedText = text
      this.vocabList.forEach(vocab => {
        const regex = new RegExp(vocab.word, 'gi')
        highlightedText = highlightedText.replace(
          regex, 
          `<span class="target-vocab">${vocab.word}</span>`
        )
      })
      return highlightedText
    },

    getRandomVocabs(vocabList, count) {
      const unmastered = vocabList.filter(vocab => vocab.situation === '未掌握')
      
      if (unmastered.length <= count) {
        return unmastered.map(vocab => vocab.newWord)
      }
      
      const shuffled = [...unmastered].sort(() => 0.5 - Math.random())
      return shuffled.slice(0, count).map(vocab => vocab.newWord)
    },

    toggleReference() {
      this.showingReference = !this.showingReference
    },

    showVocabDetail(vocab) {
      this.selectedVocab = vocab
      this.vocabModal.show()
    },

    async saveTranslation() {
      if (!this.userTranslation.trim()) {
        alert('请输入你的翻译')
        return
      }

      this.isSaving = true
      try {
        const response = await http.post('/student/translation/save', {
          englishContent: this.translationText,
          chineseContent: this.chineseTranslation,
          userTranslation: this.userTranslation,
          vocabularyList: this.vocabList.map(vocab => vocab.word)
        })

        if (response.data.code === 1) {
          alert('保存成功！')
          // 可以选择保存后自动显示参考译文
          this.showingReference = true
        } else {
          throw new Error(response.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        alert(error.message || '保存失败，请重试')
      } finally {
        this.isSaving = false
      }
    }
  }
}
</script>

<style scoped>
.ai-translation {
  background-color: #f0f9f9;
  min-height: 100vh;
  padding-bottom: 80px;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.ai-badge {
  background: linear-gradient(45deg, #40e0d0, #3bcdc0);
  color: white;
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 0.8rem;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.vocab-list {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin: 15px;
}

.vocab-item {
  display: inline-block;
  background: white;
  padding: 4px 12px;
  border-radius: 15px;
  margin: 4px;
  font-size: 0.9rem;
  border: 1px solid #eee;
  cursor: pointer;
}

.vocab-item:hover {
  background: #e3f2fd;
  border-color: #1976d2;
}

.translation-section {
  background: white;
  margin: 15px;
  border-radius: 15px;
  padding: 20px;
}

.english-text {
  font-size: 1.1rem;
  line-height: 1.8;
  margin-bottom: 20px;
}

:deep(.target-vocab) {
  background: rgba(64, 224, 208, 0.1);
  border-bottom: 2px solid #40e0d0;
  padding: 0 2px;
}

.translation-input {
  border: none;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  width: 100%;
  min-height: 120px;
  resize: none;
  margin-top: 20px;
}

.translation-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 224, 208, 0.2);
}

.bottom-tools {
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.regenerate-btn {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.regenerate-btn:hover:not(:disabled) {
  background: #3bcdc0;
}

.regenerate-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255,255,255,0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-content {
  text-align: center;
}

.spinner {
  width: 50px;
  height: 50px;
  margin-bottom: 15px;
}

.section-title {
  color: #1976d2;
  font-size: 1.1rem;
  margin-bottom: 1rem;
}

.reference-text {
  font-size: 1.1rem;
  line-height: 1.8;
  color: #333;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.vocab-explanations {
  margin-top: 1rem;
}

.vocab-explanation {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 10px;
}

.vocab-word {
  font-weight: bold;
  color: #1976d2;
  margin-bottom: 5px;
}

.vocab-details {
  font-size: 0.9rem;
}

.english-def {
  color: #666;
  margin-bottom: 3px;
}

.chinese-trans {
  color: #2e7d32;
}

/* Modal 自定义样式 */
:deep(.modal-content) {
  border: none;
  border-radius: 15px;
}

:deep(.modal-header) {
  border-bottom: 1px solid #eee;
  padding: 1rem 1.5rem;
}

:deep(.modal-title) {
  color: #333;
  font-size: 1.2rem;
}

:deep(.modal-body) {
  padding: 1.5rem;
}

.btn-success {
  background-color: #28a745;
  border-color: #28a745;
}

.btn-success:hover:not(:disabled) {
  background-color: #218838;
  border-color: #1e7e34;
}

.btn-success:disabled {
  background-color: #94d3a2;
  border-color: #94d3a2;
}
</style> 